//
//  NSString+RWAdditions.m
//  RWCategory
//
//  Created by Ray on 2021/11/14.
//

#import "NSString+RWAdditions.h"
#import "NSData+RWAdditions.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (RWCorrect)

+ (NSString *)rw_nonnullString:(id)sender
{
    if (sender == [NSNull null]) { return @"";}

    if (![sender isKindOfClass:[NSString class]]) {
        sender = [sender stringValue];
    }
    if ( sender == [NSNull null]
        || [sender isKindOfClass:[NSNull class]]
        || sender == nil
        || [sender isEqualToString:@"(null)"]
        || [sender isEqualToString:@"<null>"]
        ) {
        return @"";
    }else{
        return sender;
    }
}

+ (NSString *)rw_safeString:(id)sender {
    return [NSString rw_nonnullString:sender];
}

/// 是否是空的
- (BOOL)rw_isNonEmpty
{
    if (![self isKindOfClass:NSString.class]) return NO;
    if (self==nil || self.length==0) return NO;
    NSMutableCharacterSet *emptyStringSet = [[NSMutableCharacterSet alloc] init];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [emptyStringSet formUnionWithCharacterSet: [NSCharacterSet characterSetWithCharactersInString: @"　"]];
    if ([self length] == 0) {
        return NO;
    }
    NSString* str = [self stringByTrimmingCharactersInSet:emptyStringSet];
    return [str length] > 0;
}

/// 删除两端空格
/// @param string  被处理者
+ (NSString *)rw_deleteSpaceAtBothEnds:(NSString *)string {
    
    NSMutableCharacterSet* emptyStringSet = [[NSMutableCharacterSet alloc] init];
    [emptyStringSet formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    [emptyStringSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"　"]];
    NSString *result = [string stringByTrimmingCharactersInSet:emptyStringSet];
    return result;
}

- (NSString *)rw_deleteSpaceAtBothEnds {
    return [NSString rw_deleteSpaceAtBothEnds:self];
}


/// 删除所有空格
/// @param sender 被处理者
+ (NSString *)rw_deleteAllSpace:(NSString *)sender
{
    if ([[NSString rw_safeString:sender] isEqualToString:@""]) { return @""; }

    sender = [sender stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *components = [sender componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //    components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (SELF in %@)", @[@" ", @"\t", @"\n", @"\s"]]];
    components = [components filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != '\\s'"]];
    sender = [components componentsJoinedByString:@""];
    return sender;
}

- (NSString *)rw_deleteAllSpace {
    return [NSString rw_deleteAllSpace:self];
}

@end

@implementation NSString (RWFormatter)

/// 千分位格式 1352258900 --> 1,352,258,900.00
+ (NSString *)rw_currencyFormatWithString:(NSString *)string {
    NSString *result = [NSString rw_safeString:string];
    if ([result isEqualToString:@""]) { return @"0.00"; }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00"];// 设置格式
    result = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[result doubleValue]]];
    return result;
}

- (NSString *)rw_currencyFormat {
    return [NSString rw_currencyFormatWithString:self];
}

/// 手机号格式 13522589780 --> 135 2258 9780
+ (NSString *)rw_mobileFormatWithString:(NSString *)string {
    NSString *result = [NSString rw_safeString:string];
    if ([result isEqualToString:@""]) { return @""; }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"#,####,###0"];// 设置格式
    result = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[result doubleValue]]];
    result = [result stringByReplacingOccurrencesOfString:@"," withString:@" "];
    return result;

}

- (NSString *)rw_mobileFormat {
    return [NSString rw_mobileFormatWithString:self];
}

/// 匹配正则表达式的字符串集合
/// @param regex 正则表达式
- (NSArray *)rw_matchExpression:(NSString *)regex {
    
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if (error) {
        return  @[];
    }

    NSArray *matches = [regular matchesInString:self
                                        options:NSMatchingReportProgress
                                          range:NSMakeRange(0, self.length)];
    NSMutableArray *array = [NSMutableArray array];
    
    
    for (NSTextCheckingResult *match in matches) {
        for (int i = 0; i < [match numberOfRanges]; i++) {
            NSRange firstHalfRange = [match rangeAtIndex:i];
            if (self.length > firstHalfRange.location) {
                NSString *component = [self substringWithRange:firstHalfRange];
                [array addObject:component];
            }
        }
    }
    
    return array.copy;
}

/// 是否匹配正则表达式
/// @param regex 正则表达式
- (BOOL)rw_isMatchExpression:(NSString *)regex {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}

/// 是否是手机号码
- (BOOL)rw_isMobileNumber {
    NSString *regex = @"^((1[2-9]))\\d{9}$";
    return [self rw_isMatchExpression:regex];
}

/// 是否是 中国身份证号
- (BOOL)rw_isChinaIdNumber {
    NSString *regex = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|[xX])$)";
    return [self rw_isMatchExpression:regex];
}

/// 是否是中国 车牌号码
- (BOOL)rw_isChinaCarNumber {
    if (self.length==7) {
        //普通汽车，7位字符，不包含I和O，避免与数字1和0混淆
        NSString *regex = @"^[\u4e00-\u9fa5]{1}[a-hj-np-zA-HJ-NP-Z]{1}[a-hj-np-zA-HJ-NP-Z0-9]{4}[a-hj-np-zA-HJ-NP-Z0-9\u4e00-\u9fa5]$";
        return [self rw_isMatchExpression:regex];
    }else if(self.length==8){
        //新能源车,8位字符，第一位：省份简称（1位汉字），第二位：发牌机关代号（1位字母）;
        //小型车，第三位：只能用字母D或字母F，第四位：字母或者数字，后四位：必须使用数字;([DF][A-HJ-NP-Z0-9][0-9]{4})
        //大型车3-7位：必须使用数字，后一位：只能用字母D或字母F。([0-9]{5}[DF])
        NSString *regex = @"^[\u4e00-\u9fa5]{1}[a-hj-np-zA-HJ-NP-Z]{1}([0-9]{5}[d|f|D|F]|[d|f|D|F][a-hj-np-zA-HJ-NP-Z0-9][0-9]{4})$";
        return [self rw_isMatchExpression:regex];
    }
       return NO;
}

/// 是否是密码格式(6~16位，数字/字母/下划线其中两种)
- (BOOL)rw_isPasswordFormat
{
    NSString *regex = @"^(?![0-9]+$)(?![~!@#$%^&*()_+`\\-={}|\\[\\]\\\\:\";'<>?,./]+$)(?![A-Za-z]+$)[0-9A-Za-z~!@#$%^&*()_+`\\-={}|\\[\\]\\\\:\";'<>?,./]{8,}$";
//    NSString *regex = @"^[A-Za-z0-9_]{6,16}$";
    return [self rw_isMatchExpression:regex];
}

/// 是否都是数字 (这里可是@"0011220")
- (BOOL)rw_isAllNumber {
    NSString *regex = @"^[0-9]*$";//是否都是数字
    return [self rw_isMatchExpression:regex];
}

/// 是否是 正整数(首位必须>=1)
- (BOOL)rw_isPositive {
    NSString *regex = @"^[1-9]*$";
    return [self rw_isMatchExpression:regex];
}

/// 是否是 负整数
- (BOOL)rw_isNegative {
    NSString *regex = @"^-[1-9]*$";
    return [self rw_isMatchExpression:regex];
}

/// 是否都是英语字符(不区分大小写)
- (BOOL)rw_isEnglishAlphabet {
    NSString *regex = @"^[A-Za-z]+$";//是否都是字母
    return [self rw_isMatchExpression:regex];
}

/// 是否都是字母和数字
- (BOOL)rw_isEnglishAlphabetAndNumber {
    NSString *regex = @"^[A-Za-z0-9]+$";//是否都是字母和数字
    return [self rw_isMatchExpression:regex];
}

/// 是否都是字母和数字且长度在[6,16]
- (BOOL)rw_isEnglishAlphabetAndNumberLimit {
    NSString *regex = @"^[A-Za-z0-9]{6,16}$";//是否都是字母和数字且长度在[6,16]
    return [self rw_isMatchExpression:regex];
}

/// 是否都是中国汉字
- (BOOL)rw_isChineseCharacter {
    NSString *regex = @"^[\u4e00-\u9fa5]{0,}$";//是否都是汉字
    return [self rw_isMatchExpression:regex];
}

/// 是否包含有汉字
- (BOOL)rw_hasChineseCharacter {
    for(int i =0; i < [self length]; i++) {
        NSString *temp = [self substringWithRange:NSMakeRange(i, 1)];
        if ([temp rw_isChineseCharacter]) {
            return YES;
        }
    }
    return NO;
}

/// 获取拼音首字母(返回大写拼音首字母)
- (NSString *)rw_firstCharactor {
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:self];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}


//验证邮箱地址
- (BOOL)rw_isEmail
{
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    return [self rw_isMatchExpression:regex];

}

/// 是否是银行卡号
- (BOOL)rw_isBankCard
{
    if (self.length < 16) {
        return NO;
    }
    NSInteger oddsum = 0;     //奇数求和
    NSInteger evensum = 0;    //偶数求和
    NSInteger allsum = 0;
    NSInteger cardNoLength = (NSInteger)[self length];
    // 取了最后一位数
    NSInteger lastNum = [[self substringFromIndex:cardNoLength-1] intValue];
    //测试的是除了最后一位数外的其他数字
    NSString *bankCardNum = [self substringToIndex:cardNoLength - 1];
    for (NSInteger i = cardNoLength-1; i>=1; i--) {
        NSString *tmpString = [bankCardNum substringWithRange:NSMakeRange(i-1, 1)];
        NSInteger tmpVal = [tmpString integerValue];
        if (cardNoLength % 2 ==1 ) {//卡号位数为奇数
            if((i % 2) == 0){//偶数位置
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{//奇数位置
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    allsum = oddsum + evensum;
    allsum += lastNum;
    if ((allsum % 10) == 0) {
        return YES;
    }
    else {
        return NO;
    }
}

+ (NSString *)rw_firstLeter:(NSString *)string lower:(BOOL)isLower defaultString:(NSString *)defStr {
    //数据过滤
    if (![string isKindOfClass:NSString.class]) return defStr;
    if (string==nil||string.length<1) {return defStr;}
    NSString *noSpaceString = [[string mutableCopy] rw_deleteAllSpace];
    if (noSpaceString==nil || noSpaceString.length<1) {return defStr;}
    NSString *firstChart = [noSpaceString substringToIndex:1];
    //转化
    NSMutableString *str = [NSMutableString stringWithString:firstChart];
    CFStringTransform((CFMutableStringRef) str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str capitalizedString];
    if (isLower) {
        pinYin = [pinYin lowercaseString];
    }
    if(pinYin==nil || pinYin.length < 1) {
        return defStr;
    }
    NSString *result = [pinYin substringToIndex:1];
    NSInteger code = [result characterAtIndex:0];
    if (isLower) {//小写 { a97 z122 }
        if(!(code>=97 && code<=122)) {
            result = defStr;
        }
    }else {//大写 { A65 Z90 }
        if(!(code>=65 && code<=90)) {
            result = defStr;
        }
    }
    return result;
}

- (NSString *)rw_firstLeterForLower:(BOOL)isLower defaultString:(NSString *)defStr {
    return [NSString rw_firstLeter:self lower:isLower defaultString:defStr];
}

- (NSString *)rw_formatWithJoinString:(NSString *)symbol
                               length:(NSInteger)count
                       keepHeadLength:(NSInteger)headLength
                       keepFootLength:(NSInteger)footLength {
    if (symbol == nil || symbol.length == 0) return self;
    if (count < 0 || headLength < 0 || footLength < 0) return self;
    if ((headLength+footLength) > self.length) return self;
    NSString *subHead = [self rw_subToIndex:headLength-1]?:@"";
    NSString *subFoot = [self rw_subFromIndex:(self.length-footLength)]?:@"";
    NSMutableString *joinStr = [NSMutableString string];
    for (NSInteger i = 0; i < count; i++) {
        [joinStr appendFormat:@"%@",symbol];
    }
    return [NSString stringWithFormat:@"%@%@%@", subHead, joinStr, subFoot];
}

- (NSString *)rw_md5String {
    if (self==nil) return nil;
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)data.length, result);
    return [NSString stringWithFormat:
                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                result[0],  result[1],  result[2],  result[3],
                result[4],  result[5],  result[6],  result[7],
                result[8],  result[9],  result[10], result[11],
                result[12], result[13], result[14], result[15]
            ];
}

- (NSDictionary *)rw_jsonStringParsingToDictionary {
    if (self == nil || self.length == 0) return nil;
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [jsonData rw_dataParsingToDictionary];
}

+ (NSString *)rw_byteReadableStringWithSize:(long long)byteSize {
    if (byteSize < 0) {
        return @"0 B";
    } else if (byteSize < 1024) {
        return [NSString stringWithFormat:@"%lld B", byteSize];
    } else if (byteSize < 1024 * 1024) {
        double kSize = (double)byteSize / 1024;
        return [NSString stringWithFormat:@"%.2f KB", kSize];
    } else if (byteSize < 1024 * 1024 * 1024) {
        double kSize = (double)byteSize / (1024 * 1024);
        return [NSString stringWithFormat:@"%.2f MB", kSize];
    } else {
        double kSize = (double)byteSize / (1024 * 1024 * 1024);
        return [NSString stringWithFormat:@"%.2f GB", kSize];
    }
}

@end

@implementation NSString (RWURL)

/// 是否是 http/https的url
- (BOOL)rw_isLinkURl {
    NSString *regex = @"^(https?|ftp|file)://.+$";
    return [self rw_isMatchExpression:regex];
}

/// 提取url中的协议
- (NSString *)rw_extractUrlProtocol {
    NSString *regex = @"(\\w+)://([^/:]+)(:\\d*)?";
    NSArray *arr = [self rw_matchExpression:regex];
    NSString *protocal = @"";
    if (arr.count > 1) {
        protocal = arr[1];
    }
    return protocal;
}

/// 提取url中的域名
- (NSString *)rw_extractUrlDomain {
    NSString *regex = @"(\\w+)://([^/:]+)(:\\d*)?";
    NSArray *arr = [self rw_matchExpression:regex];
    
    NSString *domain = @"";
    
    if (arr.count > 2) {
        domain = arr[2];
    }
    return domain;
}

/// 提取url中的端口号
- (NSString *)rw_extractUrlPort {
    NSString *regex = @"\\w+://[^/:]+(:\\d*)?";
    NSArray *arr = [self rw_matchExpression:regex];
    NSString *port = @"";
    if (arr.count > 3) {
        port = arr[3];
    }
    return port;
}

/// 提取url中的参数
- (NSDictionary *)rw_extractUrlQuery {
    if (self && self.length > 0) {
        
        NSLog(@"📚链接:%@📚", self);
        
        NSMutableDictionary *parm = [[NSMutableDictionary alloc] init];
        
        //传入url创建url组件类
        NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:self];
        
        //回调遍历所有参数，添加入字典
        [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSLog(@"📚key:%@-value:%@📚", obj.name, obj.value);
            if ([obj.name rw_isNonEmpty] && obj.value) {
                [parm setObject:obj.value forKey:obj.name];
            }
        }];
        return parm.copy;
    }
    return @{};
}

/// 进行Url转义（将中文及中文字符以及:#[]@%除外的符号进行编码）
- (NSString *)rw_legalUrlEscaped {
        
    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [allowedCharacterSet addCharactersInString:@"#[]@%"];
    
    // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
//    NSString *encoded = [[NSString rw_safeString:self] stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
    
    NSUInteger const batchSize = 50;

    NSUInteger index = 0;
    NSMutableString *escaped = @"".mutableCopy;

    while (index < self.length) {
        NSUInteger length = MIN(self.length - index, batchSize);
        NSRange range = NSMakeRange(index, length);

        // To avoid breaking up character sequences such as 👴🏻👮🏽
        range = [self rangeOfComposedCharacterSequencesForRange:range];

        NSString *substring = [self substringWithRange:range];
        NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
        [escaped appendString:encoded];

        index += range.length;
    }

    return escaped;
}

@end

@implementation NSString (RWDateConver)

- (NSString *)rw_timeStampToFormat:(NSString *)format {    
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:[self doubleValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:detailDate];
}

@end

@implementation NSString (RWSubsets)

- (NSString *)rw_subToIndex:(NSUInteger)to {
    if (!self) {
        return nil;
    }
    
    if (self.length == 0) {
        return nil;
    }
    
    if(to < 0){
        return nil;
    }
    if (to > self.length - 1) {
        return self;
    }
    NSUInteger length = to + 1;
    NSRange range = NSMakeRange(0, length);
    return [self substringWithRange:range];
}

- (NSString *)rw_subFromIndex:(NSUInteger)from {
    if (from > self.length - 1 || from < 0) {
        return nil;
    }
    NSUInteger length = self.length - from;
    NSRange range = NSMakeRange(from, length);
    return [self substringWithRange:range];
}

- (NSString *)rw_subFrom:(NSUInteger)from to:(NSUInteger)to {
    if (from >= to) {
        return nil;
    }else if (from > self.length - 1 || to <0){
        return nil;
    }else if (to > self.length - 1) {
        return [self rw_subFromIndex:from];
    }
    NSUInteger length = to - from + 1;
    NSRange  range = NSMakeRange(from, length);
    return [self substringWithRange:range];
}

@end

@implementation NSString (RWRandom)

/// 小写随机串
/// @param count 位数
+ (NSString *)rw_lowercaseRandomWithCount:(NSInteger)count {
    if (count == 0) return @"";
    char data[count];

    for (int x=0;x<count;data[x++] = (char)('a'+ (arc4random_uniform(26))));
    
    return [[NSString alloc] initWithBytes:data length:count encoding:NSUTF8StringEncoding];
}

/// 大写随机串
/// @param count 位数
+ (NSString *)rw_uppercaseRandomWithCount:(NSInteger)count {
    if (count == 0) return @"";
    char data[count];

    for (int x=0;x<count;data[x++] = (char)('A'+ (arc4random_uniform(26))));
    
    return [[NSString alloc] initWithBytes:data length:count encoding:NSUTF8StringEncoding];
}

/// 大小写+数字随机串
/// @param count 位数
+ (NSString *)rw_letterAndNumberRandomWithCount:(NSInteger)count {
    if (count == 0) return @"";
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:count];
    for (int i = 0; i < count; i++)
    {
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;
}

@end

@implementation NSString (RWSize)

- (CGFloat)rw_heightWithFont:(UIFont *)font maxWidth:(CGFloat)width {
    return [self rw_sizeWithFont:font maxWidth:width maxHeight:MAXFLOAT lineSpace:0].height;
}

- (CGFloat)rw_widthWithFont:(UIFont *)font maxHeight:(CGFloat)height {
    return [self rw_sizeWithFont:font maxWidth:MAXFLOAT maxHeight:height lineSpace:0].width;
}

- (CGSize)rw_sizeWithFont:(UIFont *)font
                 maxWidth:(CGFloat)width
                maxHeight:(CGFloat)height
                lineSpace:(CGFloat)lineSpace {
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentLeft;
    
    paraStyle.lineSpacing = lineSpace;
    
    paraStyle.hyphenationFactor = 1.0;
    
    paraStyle.firstLineHeadIndent = 0.0;
    
    paraStyle.paragraphSpacingBefore = 0.0;
    
    paraStyle.headIndent = 0;
    
    paraStyle.tailIndent = 0;
    
    NSDictionary *dic = @{
        NSFontAttributeName: font,
        NSParagraphStyleAttributeName: paraStyle,
        NSKernAttributeName: @0.1f
    };
    
    CGSize size = [self boundingRectWithSize:CGSizeMake(width, height)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:dic
                                     context:nil].size;
    
    return size;
}

@end

@implementation NSString (RWCompare)

- (NSComparisonResult)rw_compareVersionByVersion:(NSString *)version {
    // Version格式是类似于1.2.3这样的
    NSArray *version1Array = [NSArray arrayWithArray:[self componentsSeparatedByString:@"."]];
    NSArray *version2Array = [NSArray arrayWithArray:[version componentsSeparatedByString:@"."]];
    NSInteger count1 = version1Array.count;
    NSInteger count2 = version2Array.count;
    
    // 从左向右比较
    for (int i = 0; i < count1 || i < count2; i++) {
        if (i >= count1) {
            if ([[version2Array objectAtIndex:i] intValue] > 0) {
                // 如果前辍相同且version1比较短，那么version2比较大（但认为5.0==5.0.0，所以这里要加上>0的判断）
                return NSOrderedAscending;
            }
        } else if (i >= count2) {
            if ([[version1Array objectAtIndex:i] intValue] > 0) {
                // 如果前辍相同且version2比较短，那么version1比较大（但认为5.0==5.0.0，所以这里要加上>0的判断）
                return NSOrderedDescending;
            }
        } else {
            if ([[version1Array objectAtIndex:i] intValue] < [[version2Array objectAtIndex:i] intValue]) {
                // 从左向右比较，如果某位上version1比version2小，那么version1<version2
                return NSOrderedAscending;
            } else if ([[version1Array objectAtIndex:i] intValue] > [[version2Array objectAtIndex:i] intValue]) {
                // 从左向右比较，如果某位上version1比version2大，那么version1>version2
                return NSOrderedDescending;
            }
        }
    }
    
    // 从左向右比较，如果所有位上version1和version2相等，那么version1==version2
    return NSOrderedSame;
}

@end
